import { useState, useEffect } from 'react';
import { Button, Card, CardContent, Dialog, DialogActions, DialogContent, DialogTitle, TextField, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, IconButton } from '@mui/material';
import { Add, Edit, Delete, Save, Cancel } from '@mui/icons-material';
import componentService from '../../services/componentService';

function Components() {
  const [components, setComponents] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [openDialog, setOpenDialog] = useState(false);
  const [editingComponent, setEditingComponent] = useState(null);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    createdBy: ''
  });

  // 获取组件列表
  const fetchComponents = async () => {
    setIsLoading(true);
    try {
      const data = await componentService.getAllComponents();
      setComponents(data);
    } catch (error) {
      console.error('获取组件列表失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchComponents();
  }, []);

  // 打开对话框（新增或编辑）
  const handleOpenDialog = (component = null) => {
    if (component) {
      setEditingComponent(component);
      setFormData({
        name: component.name,
        description: component.description,
        createdBy: component.createdBy
      });
    } else {
      setEditingComponent(null);
      setFormData({
        name: '',
        description: '',
        createdBy: ''
      });
    }
    setOpenDialog(true);
  };

  // 关闭对话框
  const handleCloseDialog = () => {
    setOpenDialog(false);
    setEditingComponent(null);
  };

  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // 提交表单（保存组件）
  const handleSubmit = async () => {
    try {
      if (editingComponent) {
        await componentService.updateComponent(editingComponent.id, formData);
      } else {
        await componentService.createComponent(formData);
      }
      // 保存成功后刷新列表
      fetchComponents();
      // 关闭对话框
      handleCloseDialog();
    } catch (error) {
      console.error('保存组件失败:', error);
    }
  };

  // 删除组件
  const handleDelete = async (id) => {
    if (window.confirm('确定要删除这个组件吗？')) {
      try {
        await componentService.deleteComponent(id);
        fetchComponents();
      } catch (error) {
        console.error('删除组件失败:', error);
      }
    }
  };

  return (
    <div>
      {/* 页面标题和添加按钮 */}
      <Card variant="outlined" sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h5" component="h2">
            组件管理
          </Typography>
          <Button 
            variant="contained" 
            startIcon={<Add />} 
            onClick={() => handleOpenDialog()} 
            sx={{ mt: 2 }}
          >
            添加组件
          </Button>
        </CardContent>
      </Card>

      {/* 组件列表表格 */}
      <TableContainer component={Paper}>
        <Table sx={{ minWidth: 650 }} aria-label="组件列表">
          <TableHead>
            <TableRow>
              <TableCell>ID</TableCell>
              <TableCell>名称</TableCell>
              <TableCell>描述</TableCell>
              <TableCell>创建者</TableCell>
              <TableCell>创建时间</TableCell>
              <TableCell>操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {components.map((component) => (
              <TableRow key={component.id}>
                <TableCell>{component.id}</TableCell>
                <TableCell>{component.name}</TableCell>
                <TableCell>{component.description}</TableCell>
                <TableCell>{component.createdBy}</TableCell>
                <TableCell>{new Date(component.createdAt).toLocaleString()}</TableCell>
                <TableCell>
                  <IconButton onClick={() => handleOpenDialog(component)}>
                    <Edit size={18} />
                  </IconButton>
                  <IconButton onClick={() => handleDelete(component.id)} color="error">
                    <Delete size={18} />
                  </IconButton>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* 组件编辑对话框 */}
      <Dialog open={openDialog} onClose={handleCloseDialog}>
        <DialogTitle>{editingComponent ? '编辑组件' : '添加组件'}</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            name="name"
            label="组件名称"
            fullWidth
            value={formData.name}
            onChange={handleInputChange}
          />
          <TextField
            margin="dense"
            name="description"
            label="组件描述"
            fullWidth
            multiline
            rows={3}
            value={formData.description}
            onChange={handleInputChange}
          />
          <TextField
            margin="dense"
            name="createdBy"
            label="创建者"
            fullWidth
            value={formData.createdBy}
            onChange={handleInputChange}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog} startIcon={<Cancel />}>
            取消
          </Button>
          <Button onClick={handleSubmit} startIcon={<Save />} variant="contained">
            保存
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}

export default Components;